// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI, {Message} from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from "axios";

Vue.config.productionTip = false
Vue.config.productionTip = false
Vue.prototype.$axios = axios

//给axios设置统一的属性
axios.defaults.baseURL = "http://localhost:8080"//统一管理后端接收到的路径
axios.defaults.withCredentials = true;//前端允许跨域，可以使用session

//设置axios请求和响应拦截
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  //获得token值，如果非空，交给后端进行验证
  var token=localStorage.getItem("token");
  if(token!=null){
    //设置请求头部信息
    config.headers.token=token;
  }
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  // console.log("response interceptor===:",response)
  response= response.data;
  if (response.code==999){
    Message.error({
      message:response.msg
    })
  }
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});

//路由守卫:拦截前端页面无故跳转
router.beforeEach((to, from, next) => {
  //console.log(to,from)
  var token=localStorage.getItem("token");
  var isAuthenticated=false;//验签/认证
  if(token){
    isAuthenticated=true;
  }

  if (to.name!='login' && !isAuthenticated) {//释放登录页面的路径
    if (to.name=='index') next() //释放展示页面的路径
    else if (to.name=='register') next() //释放注册页面的路径
    else
      next({name: 'login'})
  }
  else next()
})

Vue.use(ElementUI);
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
